package com.xca.photogallery.common;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.lang.ref.WeakReference;

/**
 * WeakReference Handler
 *
 * @param <T>
 */
public class WeakRrfHandler<T> extends Handler {
    private WeakReference<T> wrf;
    private Callback cb;

    public WeakRrfHandler(Looper looper, T t, Callback callback) {
        super(looper);
        cb = callback;
        wrf = new WeakReference<>(t);
    }

    @Override
    public void handleMessage(Message ms) {
        if (isAlive() && cb != null) {
            cb.handleMessage(ms);
        }
    }

    public T getReference() {
        return wrf.get();
    }

    /**
     * 是否还存活
     *
     * @return
     */
    public boolean isAlive() {
        T t = wrf.get();
        return t != null;
    }
}